<template>
  <div
    v-if="!loading"
    class="vc-button-list"
    :style="{gap: gap}"
  >
    <div
      v-if="compStyle['showAll']"
      class="vc-button-list-item"
      :style="getStyle({})"
    >{{ allName || '全部' }}</div>
    <div
      v-for="(data, index) in dataList"
      :key="index"
      class="vc-button-list-item"
      :style="getStyle(data)"
    >{{data["显示字段"]}}</div>
  </div>
</template>

<script setup>
import {ref, watch, nextTick, onMounted} from 'vue';
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const currValue = ref('');
const dataList = ref([{}]);
const gap = ref('');
const allName = ref('全部');
const loading = ref(true);

const init = async() => {
  loading.value = true;
  if (currNode.value.compData.dataSourceType === '') {
    currNode.value.compData.dataSourceType = '静态数据';
  }
  gap.value = props.compStyle['gap'];
  allName.value = props.compStyle['allName'];
  await nextTick(() => loading.value = false);
};

const loadDataList = async() => {
  loading.value = true;
  currValue.value = await visual.loadValue(currNode.value, {}) || '';
  dataList.value = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList.value);
  await nextTick(() => loading.value = false);
};

const getStyle = (data) => {
  const compStyle = props.compStyle || {};
  const prefix = currValue.value === (data['传值字段'] || '') ? 'selected.' : '';
  const styleList = compStyle[prefix + 'styleList'] || [];
  const style = visual.getConditionStyle(styleList, data);
  return style ? visual.parseStyle(style) : visual.parseFontStyle(compStyle);
};

watch(() => props.compStyle, () => {
  init();
}, { deep: true });

watch(() => props.node.compData?.refresh, () => {
  loadDataList();
});

onMounted(async() => {
  await init();
  await loadDataList();
});
</script>

<style scoped lang="scss">
.vc-button-list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
</style>